/**
 * @(#) Trasmettitore.java
 */

package it.unibo.iss.domotica.EDDomain;


import it.unibo.iss.domotica.converter.DomoticaJsonConverter;
import it.unibo.iss.domotica.edDomain.ConsumptionData;
import it.unibo.iss.domotica.edDomain.ISensor;
import it.unibo.iss.domotica.edDomain.Sensor;

import org.apache.log4j.Logger;

public class Transmitter extends AbstractTransmitter {
	
	private ISensor sensor;
	private boolean stopThread;
	private DomoticaJsonConverter converter;
	
	// Logger
	private Logger logger = Logger.getLogger(Transmitter.class);
	
	public Transmitter() throws Exception {
		this(null);
	}
	
	public Transmitter(ISensor sensor) throws Exception {
		if(sensor != null)
			this.sensor = sensor;
		else
			this.sensor = new Sensor();
		stopThread = false;
		converter = new DomoticaJsonConverter();
	}

	public void setStopThread(boolean stopThread) {
		this.stopThread = stopThread;
	}

	//	@Override
	public void sendData(double consumption) {
//		String msg = "\"" + sensor.getEdName() + "=" + consumption + "\"";
		ConsumptionData data = new ConsumptionData(sensor.getEdName(), consumption);
		String msg = "\"" + converter.consumptionDataToString(data) + "\"";
		try {
			M = msg;
			transmitterForward_consumptionData_receiver();
			logger.debug("Data " + msg + " sent...");
		} catch (Exception e) {
			logger.error("Exception received: " + e);
			e.printStackTrace();
			stopThread = true;
		}
	}

	@Override
	public void doJob() throws Exception {
		logger.debug("Transmitter for " + sensor.getEdName() + " started");
		
		while(!stopThread) {
			sendData(sensor.getConsumption());
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}
